package liming.tool.handle.net.root;

import liming.tool.handle.ReceiveMap;
import liming.tool.handle.net.root.base.IP;
import liming.tool.handle.net.root.base.NetType;
import liming.tool.handle.net.root.error.NetToolsException;

import java.net.InetAddress;

public class NetReceiveMap extends ReceiveMap {
    protected boolean state;//状态，在不同协议有不同状态，视具体情况来看
    protected String massage;//回复的消息
    protected NetType netType;//消息类型
    private transient IP ip;

    public NetReceiveMap() {
        super();
        ip = new IP();
        netType = NetType.ROOT;
    }

    public NetReceiveMap(ReceiveMap receiveMap) {
        super(receiveMap);
        if (receiveMap instanceof NetReceiveMap) {
            NetReceiveMap netReceiveMap = (NetReceiveMap) receiveMap;
            ip = netReceiveMap.ip;
            state = netReceiveMap.state;
            massage = netReceiveMap.massage;
            netType = netReceiveMap.netType;
        } else
            throw new NetToolsException("Packet type matching failed: " + receiveMap.getClass().getName() + " ==> " + NetReceiveMap.class.getName());
    }

    public NetReceiveMap(NetReceiveMap netReceiveMap) {
        super(netReceiveMap);
        ip = netReceiveMap.ip;
        state = netReceiveMap.state;
        massage = netReceiveMap.massage;
        netType = NetType.ROOT;
    }

    public synchronized void removeIP() {
        ip.clear();
        ip = null;
    }

    public synchronized void removeAll() {
        clear();
        removeIP();
        state = false;
        massage = null;
        netType = NetType.ROOT;
    }

    public NetType getNetType() {
        return netType;
    }

    public NetReceiveMap setIP(InetAddress inetAddress, int port) {
        if (ip == null) ip = new IP(inetAddress, port);
        else ip.setIP(inetAddress, port);
        return this;
    }

    public NetReceiveMap setIP(IP ip) {
        this.ip = ip;
        return this;
    }

    public InetAddress getInetAddress() throws NetToolsException {
        return ip.getInetAddress();
    }

    public int getPort() throws NetToolsException {
        return ip.getPort();
    }

    public boolean isState() {
        return state;
    }

    public NetReceiveMap setState(boolean value) {
        state = value;
        return this;
    }

    public String getMassage() {
        return massage;
    }

    public void setMassage(String massage) {
        this.massage = massage;
    }

    @Override
    public String toString() {
        return "NetReceiveMap{" +
                "netType=" + netType +
                ", ip=" + ip +
                ", state=" + state +
                ", massage='" + massage + "'," +
                super.toString() +
                '}';
    }
}
